import cloneDeep from 'lodash/cloneDeep'
import request from '@/utils/request'
import { GFCD } from '@/utils/utils'
import { processingConstant } from '@ve/utils/utils'
import { translateTitle } from '@/utils/i18n'
// 统一请求
function requestApi(options = {}, callback) {
  /*
  options:{
    api:'',//接口
    method:'',//方法
    data:{},//参数
  }
  */
  //使用自定义参数
  //发起请求
  return request({
    url: GFCD('dams', 'domain') + options.api,
    method: 'post',
    data: {
      data: JSON.stringify(options.data),
      method: options.method,
    },
  }).then((res) => {
    //this.getInfo.data.requestData = isEmpty(getDataKey) ? res.data : res.data[getDataKey]
    //添加回调
    callback && callback.call(this, res)
  })
}

//异步await
async function deleteImte(item) {
  //循环删除节点
  for (let i = 0; i < item.length; i++) {
    if (!item[i] || !item[i]._id) {
      continue
    }
    await this.$store.dispatch('diy/removeModule', item[i])
  }
}

//初始化保存
export function initSaveRevocation(vm) {
  //初始化判断
  const getRedoInfo = vm.$store.getters['diy/getDeletePages'] || {}
  if (!getRedoInfo[vm.getSelectLayerId]) {
    saveRevocation.call(vm)
  }
}

//保存动作
export function saveRevocation() {
  //存储删除的组件
  const getPageInfo = cloneDeep(this.$store.getters['diy/getPageModules'])
  if (getPageInfo) {
    //获取vuex的数据
    const getRedoInfo = this.$store.getters['diy/getDeletePages'] || {}
    //获取当前选择的页的缓存
    const getStorePage = getRedoInfo[this.getSelectLayerId] || []
    //数据一样不缓存
    if (getStorePage.length && JSON.stringify(getStorePage[getStorePage.length - 1]) === JSON.stringify(getPageInfo)) {
      return
    }
    //缓存数据
    this.$store.dispatch('diy/setDeletePages', {
      layerid: this.getSelectLayerId,
      data: getPageInfo,
    })
  }
}

//撤回
export function revocation() {
  //撤销
  //获取上一次记录的数据
  const $this = this
  const selectLayerId = $this.getSelectLayerId
  const modules = $this.$store.getters['diy/getDeletePages'][selectLayerId]
  //判断最后一个是否相等
  if (JSON.stringify($this.getPageModules) === JSON.stringify(modules[modules.length - 1])) {
    if (modules.length === 1) return
    //删除list
    const deleteList = $this.getPageModules
    deleteImte.call($this, [deleteList[deleteList.length - 1]])

    //删除页面数据
    $this.$store.dispatch('diy/removeDeletePages', {
      layerid: selectLayerId,
      data: modules,
    })
  }
  //自动执行
  ; (async function reloadFun(modules) {
    let len = modules.length === 0 ? 0 : modules.length - 1
    //删除list
    const deleteList = modules[len] || $this.getPageModules
    if (deleteList.length && len > 0) {
      await $this.$store.dispatch('diy/removeModule', deleteList[deleteList.length - 1])
    }
    //获取pagemodule
    let pages = modules[len] || []
    if (len === 0) {
      pages = modules[len][0] || modules[len]
    }
    if (!Array.isArray(pages)) {
      pages = [pages]
    }
    //添加数据
    await $this.$store.dispatch('diy/setPageModules', pages)
    if (len <= 2) return
    //删除数据
    await $this.$store.dispatch('diy/removeDeletePages', {
      layerid: selectLayerId,
      data: modules,
    })
  })(modules)
}

//清空
export function clear() {
  const $this = this
  //清空操作
  $this
    .$confirm(translateTitle('Ve.utils.清空操作提示'), translateTitle('Ve.utils.提示'), {
      confirmButtonText: translateTitle('Ve.utils.确定'),
      cancelButtonText: translateTitle('Ve.utils.取消'),
      type: 'warning',
    })
    .then(() => {
      const item = cloneDeep($this.getPageModules)
      if (!item.length) {
        return
      }
      //存储信息
      saveRevocation.call($this)

      //循环删除节点
      deleteImte.call($this, item)

      //提示信息
      $this.$message({
        type: 'success',
        message: translateTitle('Ve.utils.删除成功'),
      })
    })
    .catch(() => {
      $this.$message({
        type: 'info',
        message: translateTitle('Ve.utils.已取消删除'),
      })
    })
}

//获取ID
function getKeyId(vm) {
  return `${vm.$store.getters['user/uid']}_${vm.$store.getters['user/appId']}_${vm.$route.query.ID}`
}

//缓存历史文件
export async function setlocalStorage(vm, info) {
  //获取页面KEY
  const key = getKeyId(vm)
  //克隆页面信息
  const pageInfo = cloneDeep(info)
  //获取vuex中缓存
  const getHistoryData = vm.$store.getters['diyHistoryData/historyData'] || []
  //保存数据一样不存储
  if (getHistoryData.length) {
    //深拷贝PAGEINFO对象
    let getNewInfo = {}
    if (typeof getHistoryData[0].PAGE_INFO === 'string') {
      getNewInfo = JSON.parse(getHistoryData[0].PAGE_INFO || '{}')
    } else {
      getNewInfo = cloneDeep(getHistoryData[0].PAGE_INFO || {})
    }
    //时间戳改为一样
    getNewInfo.TIMECODE = pageInfo.TIMECODE
    if (JSON.stringify(getNewInfo) === JSON.stringify(pageInfo)) {
      return
    }
  }
  //保存缓存的数据
  const saveObj = {
    HISTORY_COUNT: '20',
    PAGE_CONFIG: {
      PAGE_INFO: pageInfo,
      TIME_CODE: JSON.parse(pageInfo).TIMECODE,
      PAGE_ID: key,
      USER_ID: vm.$store.getters['user/uid'],
      APP_CODE: processingConstant(vm, '#APP_CODE#'),
    },
  }
  console.log('历史记录保存', saveObj)
  //设置缓存
  await requestApi(
    {
      api: GFCD('dams', 'baseUrl'),
      method: 'page.config.mongodb.history',
      data: saveObj,
    },
    function () {
      //重新获取数据
      setTimeout(() => {
        getlocalStorage(vm)
      }, 1000)

    }
  )
}

//获取缓存
export async function getlocalStorage(vm) {
  await requestApi(
    {
      api: GFCD('dams', 'baseUrl'),
      // method: 'dams.mongodb.history.config.query',
      method: 'system.log.page.json.history.info.query',
      data: { '#LIMIT#': 1, '#PAGE_SIZE#': 10, PAGE_ID: getKeyId(vm) + '', USER_ID: processingConstant(vm, '#USER_ID#') },
    },
    function (res) {
      if (!res || !res.data) {
        return
      }
      let getItem = []
      if (res.data.data) {
        getItem = res.data.data.data
      } else {
        //获取缓存
        getItem = res.data['dams.mongodb.history.config.query'].data
      }
      getItem.forEach((element, index) => {
        element['PAGENAME'] = '历史版本' + (index + 1)
      })
      //获取到的结果加入到vux
      vm.$store.dispatch('diyHistoryData/saveHistory', getItem)
    }
  )
}

//删除缓存
export function removelocalStorageItem() {
  console.log('触发删除')
  localStorage.removeItem('wmsv2_diy_save_pageinfo')
}
